/**
 * 
 */
package org.youisoft.summer.evaluator.function.service;

import org.youisoft.summer.evaluator.InvokeException;
import org.youisoft.summer.evaluator.connector.Connector;
import org.youisoft.summer.evaluator.context.CalContext;
import org.youisoft.summer.evaluator.function.AbstractFunction;
import org.youisoft.summer.evaluator.message.Message;
import org.youisoft.summer.evaluator.operator.Operator;
import org.youisoft.summer.evaluator.operator.base.MapOperator;
import org.youisoft.summer.evaluator.operator.base.MessageOperator;

/**
 * @author zijiang.jl
 *
 */
public class EndpointFunction extends AbstractFunction{


	@Override
	protected boolean checkOperator(int index, Operator<?> operator) {
		if(index==0&&Connector.class.isAssignableFrom(operator.value().getClass())) return true;
		if(MapOperator.class.isAssignableFrom(operator.getClass())) return true;
		return false;
	}
	
	@Override
	protected boolean checkAddendumOperator(Operator<?> operator) {
		return MessageOperator.class.isAssignableFrom(operator.getClass());
	}



	@Override
	public <C, R, P> Operator<?> doBracketInvoke(CalContext<C, R, P> context,
			Operator<?>... operator) throws InvokeException {
		System.out.println("in EndpointFunction");
		Connector con=Connector.class.cast(operator[0].value());
		MessageOperator mo=MessageOperator.class.cast(operator[operator.length-1]);
		con.produceMessage(mo.value());
		return null;
	}

	@Override
	public <C, R, P> Operator<?> doParenthesisInvoke(
			CalContext<C, R, P> context, Operator<?>... operator)
			throws InvokeException {
		System.out.println("in EndpointFunction");
		Connector con=Connector.class.cast(operator[0].value());
		if(!context.hasPayload()){
			Message msg=con.consumeMessage();
			if(msg!=null) {
				context.setPayload(true);
				MessageOperator mo=new MessageOperator(msg);
				return mo;
			}
		}
		return null;
	}

	
	@Override
	protected int minOperatorCount() {
		return 1;
	}
	
}
